//
//  UIColor+Extension.swift
//  ZZY微博
//
//  Created by 庄壮勇 on 2018/1/17.
//  Copyright © 2018年 Personal. All rights reserved.
//

import UIKit

extension UIColor {
    
    class func randomColor() -> UIColor {
        
        // 0~255
        let r = CGFloat(arc4random() % 256) / 255.0
        let g = CGFloat(arc4random() % 256) / 255.0
        let b = CGFloat(arc4random() % 256) / 255.0
        
        return UIColor(red: r, green: g, blue: b, alpha: 1.0)
    }
    
    /**
     4      Make color with hex string
     5      - parameter hex: 16进制字符串
     6      - returns: RGB
     7      */
    static func colorWithHexString (hex: String) -> UIColor {
    
        var cString: String = hex.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines).uppercased()
    
             if (cString.hasPrefix("#")) {
                cString = (cString as NSString).substring(from: 1)
             }
        if (cString.hasPrefix("0x") || cString.hasPrefix("0X")) {
            cString = (cString as NSString).substring(from: 2)
        }
        
             if (cString.characters.count != 6) {
                return UIColor.gray
             }
    
        let rString = (cString as NSString).substring(to: 2)
        let gString = ((cString as NSString).substring(from: 2) as NSString).substring(to: 2)
        let bString = ((cString as NSString).substring(from: 4) as NSString).substring(to: 2)
    
             var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
        Scanner(string: rString).scanHexInt32(&r)
        Scanner(string: gString).scanHexInt32(&g)
        Scanner(string: bString).scanHexInt32(&b)
    
             return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(1))
         }
    
}
